const action = require("../action");
const maxPageObj = require('../config').maxPageObj || 25;
const convertDate = function(utc) {
    let date = new Date(utc);
    return date.toLocaleDateString();
}

module.exports = {
    'GET /': async (ctx, next) => {
        let currentPage = ctx.request.query.page || 1;
        let deliveryData = await action.delivery.getByPage(currentPage, maxPageObj); deliveryData = deliveryData.data.rows;
        let deliveryAmount = await action.delivery.count(); deliveryAmount = deliveryAmount.data;        
        let totalPage = parseInt(deliveryAmount / maxPageObj) + 1;        
        
        // 当前页最大编号， 即从大往小排列第一个元素
        let i = deliveryAmount - (currentPage - 1) * maxPageObj;
        deliveryData.forEach(delivery => {
            delivery.createdAt = convertDate(delivery.createdAt);
            delivery.showId = i;
            i--;
        });
        
        let pageTabs = [];
        for (let i = 1; i <= totalPage; i++) {
            pageTabs.push({
                "url": "/?page=" + i,
                "pageNum": i,
            });
        }

        ctx.render('main.html', {
            "ui": {
                "title": "快递仓库",
                "pagination":{
                    "pageTabs": pageTabs,
                    "currentPage": parseInt(currentPage),
                    "totalPage": totalPage
                },
            },
            "deliveryData": deliveryData
        });
    }
};

